<?php

/* Class provides basic encapsulation of database operations. */
class Db
{
   private $host;
   private $username;
   private $password;
   private $database;
   
   private $link;
   
   /* Class constructor. */
   public function __construct($host, $username, $password)
   {
      $this->host = $host;
      $this->username = $username;
      $this->password = $password;
   }

   /* Closes database connection during desrutction of object. */
   public function __destruct()
   {
      $this->Close();
   }
      
   /* Function establishes the connection to specified database. */
   public function Connect($databaseName)
   {
      $this->database = $databaseName;
      
      // Connect to database server
      $this->link = mysql_connect($this->host, $this->username, $this->password);
      if (!$this->link)
      {
         trigger_error('Cannot connect to database server');
         return false;
      }
      
      // Select specific database
      if (!mysql_select_db($this->database, $this->link))
      {
         trigger_error('Cannot find the requested database');
         return false;
      }
      
      return true;
   }
   
   public function Select($query)
   {
      return mysql_query($query, $this->link);
   }

   public function SelectScalar($query)
   {
      $result = mysql_query($query, $this->link);
      if (mysql_num_rows($result) != 1)
         return false;
         
      $values = mysql_fetch_array($result);
      
      mysql_free_result($result);
      
      return $values[0];
   }
      
   public function Insert($query)
   {
      $result = mysql_query($query, $this->link);
      if ($result === false)
         return -1;
      
      $result = mysql_insert_id($this->link);
      if ($result === false)
         return -1;
         
      return $result;
   }
   
   public function FetchNext($resource)
   {
      return mysql_fetch_array($resource);
   }
   
   public function Free($resource)
   {
      mysql_free_result($resource);
   }

   /* Provides stats of current database link. */
   public function GetStatus()
   {
      return mysql_stat($this->link);
   }
   
   /* Closes current connection to database. */
   public function Close()
   {
      if ($this->link)
         mysql_close($this->link);
   }
}
?>